﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ProgramMain.Database;
using ProgramMain.Database.SimpleOpticNetDBTableAdapters;
using ProgramMain.Framework;

namespace ProgramMain.OpticNet
{
    public partial class VertexMapDesignPanel : ProgramMain.Framework.BaseDetailCtl
    {
        public VertexMapDesignPanel()
        {
            InitializeComponent();
            zoomVertex.Value = 10;
       //     SetStyle(ControlStyles.SupportsTransparentBackColor, true);

            vertexImages.Images.Add(Properties.Resources.vertex_24);
            vertexImages.Images.Add(Properties.Resources.transitvertex_24);
            vertexImages.Images.Add(Properties.Resources.office_24);
            SetHistory = false;
           
        }

        private void CreatePlanState()
        {
            List<PlanState> planStates = new List<PlanState>();
            planStates.Add(new PlanState(1, "только кабели"));
            planStates.Add(new PlanState(2, "только муфты"));
            planStates.Add(new PlanState(3, "все элементы"));

            lookPlanState.Properties.DataSource = planStates;
            lookPlanState.EditValue = 1;
            
        }

        public int Zoom
        {
            get
            {
                return zoomVertex.Value;
            }
            set
            {
                if (zoomVertex.Value != value)
                {
                    zoomVertex.Value = value;
                }
            }
        }
        private bool SetHistory { get; set; }
        private Stack<int?> _backStack = new Stack<int?>();
        private Stack<int?> _nextStack = new Stack<int?>();

        public event EventHandler ZoomChanged;
        public event EventHandler<IntEvent> BeforeVertexJump;
        public event EventHandler<StringEvent> SendStringMessage;

        private void _zoomChanged(object sender, EventArgs e)
        {
            if (ZoomChanged != null) ZoomChanged(this, e);
        }

        private void popupVertexView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (listVertex.SelectedItems.Count > 0)
            {
                SimpleOpticNetDB.VertexesRow row = listVertex.SelectedItems[0].Tag as SimpleOpticNetDB.VertexesRow;
                if (row != null)
                {
                    EditVertex(row.ID, Point.Empty);
                }
            }
        }

        private void popupMapView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (listVertex.SelectedItems.Count > 0)
            {
                SimpleOpticNetDB.VertexesRow row = listVertex.SelectedItems[0].Tag as SimpleOpticNetDB.VertexesRow;
                if (row != null)
                {
                    FrmOpticMap map = FrmOpticMap.ShowForm();
                    map.SetCenterMapObject(row.Longitude, row.Latitude);
                    map.AddVertesLighted(row.ID);
                }
            }
        }

        private void popupVertexRedirect_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (listVertex.SelectedItems.Count > 0)
            {
                SimpleOpticNetDB.VertexesRow row = listVertex.SelectedItems[0].Tag as SimpleOpticNetDB.VertexesRow;
                if (row != null)
                {
                    OnBeforeVertexJump(row.ID);
                }
            }
        }

        private void OnBeforeVertexJump(int? objectID)
        {
            if (BeforeVertexJump != null) BeforeVertexJump(this, new IntEvent(objectID));
        }

        private void popupVertexListView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (listVertex.SelectedItems.Count > 0)
            {
                SimpleOpticNetDB.VertexesRow row = listVertex.SelectedItems[0].Tag as SimpleOpticNetDB.VertexesRow;
                if (row != null)
                {
                    FrmVertexes frmVertexes = FrmVertexes.ShowForm();

                    frmVertexes.SetActiveVertex(row.ID);
                    frmVertexes.SetTableActive(PresentFormType.InVertexes);
                }
            }
        }

        private void barConnection_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (listVertex.SelectedItems.Count > 0)
            {
                SimpleOpticNetDB.VertexesRow row = listVertex.SelectedItems[0].Tag as SimpleOpticNetDB.VertexesRow;
                if (row != null)
                {
                    FrmFibrePointDetail fibrePointDetail = new FrmFibrePointDetail();
                    fibrePointDetail.VertexID = row.ID;
                    fibrePointDetail.EquipVertexID = null;
                    fibrePointDetail.ShowForm();
                }
            }
        }

        public string VertexAdres { get; private set; }
        private void CreateVertexes()
        {
            listVertex.Items.Clear();
            VertexesTableAdapter vertexesTableAdapter = new VertexesTableAdapter();
            vertexesTableAdapter.ClearBeforeFill = true;
            vertexesTableAdapter.SelectCommandTimeout = Properties.Settings.Default.LongQueryTimeout;
            SimpleOpticNetDB.VertexesDataTable vertexesDataTable = vertexesTableAdapter.GetData(null, null, null, null,
                                                                                                null, DetailID, null,
                                                                                                null, null);
            foreach (SimpleOpticNetDB.VertexesRow item in vertexesDataTable.Cast<SimpleOpticNetDB.VertexesRow>())
            {
                string caption = item.IsCaptionNull() ? "" : item.Caption;
                ListViewItem vertex = new ListViewItem(caption);
                vertex.Tag = item;
                vertex.SubItems.Add(item.ID.ToString());

                if (item.IsIsEmptyNull() || item.IsEmpty)
                {
                    // BitmapVertex = Properties.Resources.transitvertex_24;
                    vertex.ImageIndex = 1;
                }
                else
                {
                    if (!item.IsImageIndexNull())
                        // BitmapVertex = Properties.Resources.office_24;
                        vertex.ImageIndex = 2;
                    else
                    {
                        // BitmapVertex = Properties.Resources.vertex_24;
                        vertex.ImageIndex = 0;
                    }
                }

                listVertex.Items.Add(vertex);
                
            }
            if (SendStringMessage != null && listVertex.Items.Count > 0)
            {
                try
                {
                    SimpleOpticNetDB.VertexesRow item = (SimpleOpticNetDB.VertexesRow)listVertex.Items[0].Tag;
                    VertexAdres = item.IsAddressNull() ? "" : item.Address;
                }
                catch (Exception)
                {
                }
                SendStringMessage(this, new StringEvent(listVertex.Items[0].Text));
               
            }
        }

        private void listVertex_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            popupVertexRedirect_ItemClick(sender, null);
        }

        private void VertexMapDesignPanel_DetailIDChanged(object sender, DetailEventArgs e)
        {
            CreateVertexes();

            if (SetHistory)
            {
                int? d = null;
                if (_backStack.Count > 0) d = _backStack.Peek();
                if (d != e.OldDetailID) _backStack.Push(e.OldDetailID);
            }

            btFirst.Enabled = _backStack.Count > 0;
            btBack.Enabled = _backStack.Count > 0;
            btNext.Enabled = _nextStack.Count > 0;
            btLast.Enabled = _nextStack.Count > 0;
            SetHistory = true;
        }

        private void EditVertex(int ObjectID, Point newPt)
        {
            VertexDetail dialog = new VertexDetail();

            vertexesTableAdapter.SelectCommandTimeout = ProgramMain.Properties.Settings.Default.LongQueryTimeout;
            vertexesTableAdapter.ClearBeforeFill = true;
            vertexesTableAdapter.Fill(simpleOpticNetDB.Vertexes, ObjectID, null, null, null, null, null, null, null, null);
            dialog.dataSource = dsVertexes;
            if (simpleOpticNetDB.Vertexes.Count > 0)
            {
                BaseModalDetailCtl.ShowModeTypes ShowMode = BaseModalDetailCtl.ShowModeTypes.View;

                DialogResult dlgRes = dialog.ShowModal(ShowMode);

            }
        }

        private void btBack_Click(object sender, EventArgs e)
        {
            SetHistory = false;
            int? d = null;
            if (_backStack.Count > 0) d = _backStack.Pop();
            if (d != null)
            {
                _nextStack.Push(DetailID);
                OnBeforeVertexJump(d);
            }
        }

        private void btNext_Click(object sender, EventArgs e)
        {
            SetHistory = false;
            int? d = null;
            if (_nextStack.Count > 0) d = _nextStack.Pop();
            if (d != null)
            {
                _backStack.Push(DetailID);
                OnBeforeVertexJump(d);
            }
        }

        private void btFirst_Click(object sender, EventArgs e)
        {
            SetHistory = false;
            int? d = null;
            if (_backStack.Count > 0 && (_nextStack.Count == 0 || _nextStack.Peek() != DetailID)) _nextStack.Push(DetailID);
            while (_backStack.Count > 0)
            {
                d = _backStack.Pop();
                if (d != null && _nextStack.Peek() != d && _backStack.Count > 0)
                    _nextStack.Push(d);
            }
            OnBeforeVertexJump(d);
        }

        private void btLast_Click(object sender, EventArgs e)
        {
            SetHistory = false;
            int? d = null;
            if (_nextStack.Count > 0 && (_backStack.Count == 0 || _backStack.Peek() != DetailID)) _backStack.Push(DetailID);
            while (_nextStack.Count > 0)
            {
                d = _nextStack.Pop();
                if (d != null && _backStack.Peek() != d && _nextStack.Count > 0)
                    _backStack.Push(d);

            }
            OnBeforeVertexJump(d);
        }

        public class VertexStateEvent : EventArgs
        {
            private VertexMapState _state;
            public VertexMapState State
            {
                get { return _state; }
            }
            public VertexStateEvent(VertexMapState state)
            {
                _state = state;
            }
        }

        public event EventHandler<VertexStateEvent> VertexStateChanged;
        public event EventHandler<IntEvent> RefreshVertex;

        private void btConnection_CheckedChanged(object sender, EventArgs e)
        {
            VertexMapState mapState = btConnection.Checked ? VertexMapState.Connection : VertexMapState.None;
            labelStatus.Text = btConnection.Checked ? "Включен режим разварки" : "";
            if (VertexStateChanged != null) VertexStateChanged(this, new VertexStateEvent(mapState));
        }

        private void btRefresh_Click(object sender, EventArgs e)
        {
            CreateVertexes();
            if (RefreshVertex != null) RefreshVertex(this, new IntEvent(null));
        }

        public event EventHandler<BoolEvent> AllConnectionChanged;
        private void checkAllConnect_CheckedChanged(object sender, EventArgs e)
        {
            if(AllConnectionChanged != null) AllConnectionChanged(this, new BoolEvent(checkAllConnect.Checked));
        }
        public event EventHandler Printing;
        private void btPrint_Click(object sender, EventArgs e)
        {
            if (Printing != null) Printing(this, EventArgs.Empty);
        }

        public event EventHandler<IntEvent> PlanStateChanged;

        private void lookPlanState_EditValueChanged(object sender, EventArgs e)
        {
            int i = (int) lookPlanState.EditValue;
            if (PlanStateChanged != null) PlanStateChanged(this, new IntEvent(i));
        }

        private void VertexMapDesignPanel_Load(object sender, EventArgs e)
        {
            CreatePlanState();
        }
        

    }

    class PlanState
    {
       public int ID { get; private set; }
       public string Caption { get; private set; }

        public PlanState(int id, string caption)
        {
            ID = id;
            Caption = caption;
        }
    }
}
